﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FlowBasis.Security.Principal;
using FlowBasis.Security;

namespace FlowBasis.Web.Security
{
    public class HttpUserContextService : IUserContextService    
    {
        public HttpUserContextService()
        {
        }

        public bool IsAuthenticated
        {
            get 
            {
                var user = HttpContext.Current.User;
                if (user != null && user.Identity != null)
                {
                    return user.Identity.IsAuthenticated;
                }
                else
                {
                    return false;
                }
            }
        }

        public object UserId
        {
            get 
            {
                var user = HttpContext.Current.User as IPrincipalWithDisplayNameAndId;
                if (user != null)
                {
                    return user.UserId;
                }
                else
                {
                    return null;
                }
            }
        }

        public string DisplayName
        {
            get
            {
                var user = HttpContext.Current.User as IPrincipalWithDisplayNameAndId;
                if (user != null)
                {
                    return user.DisplayName;
                }
                else
                {
                    return null;
                }
            }
        }

        public bool HasPermission(string permissionName)
        {
            var user = HttpContext.Current.User as IPrincipalWithPermissions;
            if (user != null)
            {
                return user.HasPermission(permissionName);
            }
            else
            {
                return false;
            }
        }

        public void RequirePermission(string permissionName)
        {
            if (!this.HasPermission(permissionName))
            {
                throw new PermissionDeniedException(permissionName);
            }
        }

    }
}
